"""
将模块序列化储存
"""
from .processors import *
from core.utils.general import dynamic_import
class ProcessorSequence():
    """模块序列化类
    
    能够接收自定义类, 会检测类名中是否存在"."(比如task.modules.custom.CustomCls)

    如果存在"."则说明为按路径导入飞自有模块,会进行动态加载自定义模块
    
    sample:
        cfg = {
            "SteamPull":{
                "keys":{
                    "out": "input_data",
                },
                "pull_url" : "rtmp://218.94.155.86:1936/live/livestream_74_1"
                "pull_size": [1290,1080,720]
            },
            "project.traffic.Split":{
                "keys":{
                    "in" : "input_data",
                    "out": "split_data",
                },
                "crop_size" : [1280,720]
                "stride": [640, 360]
            },
        }
        其中Split类就是自定义类
    """
    def __init__(self, cfg:dict):
        self.processor_list = []
        for cls_name, cls_cfg in cfg.items():
            if "." in cls_name:
                path_, cls_name_ = cls_name.rsplit(".",1)
                if cls_cfg is None:
                    self.processor_list.append(dynamic_import(cls_name_,path_)())
                else:
                    self.processor_list.append(dynamic_import(cls_name_,path_)(**cls_cfg))
            else:
                if cls_cfg is None:
                    self.processor_list.append(eval(cls_name)())
                else:
                    self.processor_list.append(eval(cls_name)(**cls_cfg))

    def set(self,data):
        for processor in self.processor_list:
            processor.set(data)

    def start(self):
        for processor in self.processor_list:
            processor.start()

    def __call__(self, data):
        for processor_ in self.processor_list:
            data = processor_(data)
        return data
    
    def close(self):
        for processor_ in self.processor_list:
            processor_.close()